<template>
  <div class="department-container">
    <div class="top">
      <h2>{{ departmentName }}文件列表</h2>
      <button class="logout-btn" @click="logout">退出登录</button>
    </div>
    <div class="action-bar">
      <button class="add-btn" @click="openUploadDialog">新增文件</button>
      <div class="search-container">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索文件名称..."
          class="search-input"
        >
      </div>
    </div>
    <!-- 显示加载状态 -->
    <div v-if="departmentsStore.loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载文件中...</p>
    </div>

    <!-- 显示错误信息 -->
    <div v-else-if="departmentsStore.error" class="error-message">
      <p>{{ departmentsStore.error }}</p>
    </div>

<!-- 显示文件列表 -->
    <FileList v-else :files="filteredFiles" @fileDeleted="handleFileDeleted" />

    <!-- 上传对话框 -->
    <div v-if="isUploadDialogOpen" class="dialog-overlay">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>上传文件到{{ departmentName }}</h3>
          <button class="close-btn" @click="closeUploadDialog">&times;</button>
        </div>
        <FileUpload
          :default-department-id="departmentId"
          @upload-success="closeUploadDialog"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watchEffect } from 'vue'
import { useDepartmentsStore } from '../stores/departments'
import { useRoute, useRouter } from 'vue-router'
import FileList from '../components/FileList.vue'
import FileUpload from '../components/FileUpload.vue'

const route = useRoute()
const router = useRouter()
const departmentId = ref(null)
const departmentsStore = useDepartmentsStore()
const departmentName = ref('')
const searchQuery = ref('')
const isUploadDialogOpen = ref(false)

// 监听路由变化，确保科室ID正确更新
watchEffect(() => {
  // 将路由参数中的科室ID转换为数字
  departmentId.value = Number(route.params.id)
  // 设置当前科室
  departmentsStore.setCurrentDepartment(departmentId.value)
  // 获取科室名称
  departmentName.value = departmentsStore.getDepartmentName(departmentId.value)
})

// 组件挂载时获取文件数据
onMounted(() => {
  console.log('DepartmentView: 组件挂载，开始获取文件数据')
  // 确保科室ID已设置
  if (departmentId.value) {
    departmentsStore.fetchFiles()
  } else {
    console.error('DepartmentView: 科室ID未设置，无法获取文件数据')
  }
})

// 计算属性：根据搜索词过滤文件
const filteredFiles = computed(() => {
  // 确保先获取最新的科室文件
  const currentFiles = departmentsStore.filteredFiles
  if (!searchQuery.value) {
    return currentFiles
  }
  return currentFiles.filter(file =>
    file.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 退出登录函数
const logout = () => {
  // 清除登录状态
  localStorage.removeItem('isLoggedIn')
  // 触发storage事件，通知App.vue更新状态
  window.dispatchEvent(new StorageEvent('storage', {
    key: 'isLoggedIn',
    oldValue: 'true',
    newValue: null,
    storageArea: localStorage
  }))
  // 重定向到登录页面
  router.push('/login')
}

// 打开上传对话框
const openUploadDialog = () => {
  isUploadDialogOpen.value = true
}

// 关闭上传对话框
const closeUploadDialog = () => {
  isUploadDialogOpen.value = false
}

// 处理文件删除事件
const handleFileDeleted = (id) => {
  console.log('DepartmentView: 文件已删除，ID:', id);
  // 调用store中的方法更新数据
  departmentsStore.fetchFiles();
}
</script>

<style scoped>
.department-container {
  width: 100%;
  padding: 20px;
}

.top {
  display: flex;
  border-bottom: 2px solid #42b983;
  margin-bottom: 30px;
}

h2 {
  text-align: center;
  margin: auto;
  color: #333;
  padding-bottom: 0.5rem;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #c0392b;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.add-btn {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.add-btn:hover {
  background-color: #3aa876;
}

.search-container {
  display: flex;
  flex: 1;
  max-width: 400px;
  margin-left: 20px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #42b983;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  padding: 20px;
  background-color: #ffebee;
  color: #c62828;
  border-radius: 4px;
  margin-bottom: 20px;
}

</style>